package com.sunsharing.flow.model.node;

import com.sunsharing.common.anno.Factory;
import com.sunsharing.common.utils.DynamicString;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.flow.exe.ExecutionContext;
import com.sunsharing.flow.exe.WorkFlowService;
import com.sunsharing.flow.model.Node;
import com.sunsharing.flow.model.Transition;
import org.apache.log4j.Logger;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-5-13
 * Time: 下午11:04
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="OrFork")
public class OrFork extends Node {
    Logger logger = Logger.getLogger(OrFork.class);

    String expresstion = "";

    private String expressEval(ExecutionContext executeContext)
    {
        if(StringUtils.isBlank(expresstion))
        {
            return null;
        }
        DynamicString ds = new DynamicString(expresstion);
        Map par = executeContext.getToken().getAllPar();
        String trans = ds.convert(par);
        try
        {
            String output = WorkFlowService.evalStr(trans);
            return this.getLeavingTransitionByExpresstion(output);
        }catch (Exception e)
        {
            logger.error("转换JS出错",e);
        }
        return null;
    }
    /**
     * 功能描述:
     *    执行任务
     */
    public void execute(ExecutionContext executeContext) {

        //把当前节点加入执行节点
        executeContext.getToken().addExecutedNode(this);

        String transitionName = expressEval(executeContext);

//        if (orForkDelegation == null) {
//            throw new RuntimeException("[" + this.getName() + " ]鉴定节点[" +
//                    this.getId() + "]的鉴定委托类为空,请检查工作流配置!");
//        }


        Transition transition = null;
        //如果迁移名不为空
        if (transitionName != null && transitionName.length() > 0) {

//            for (int i = 0; i < transitionNames.length; i++) {
//                if (logger.isDebugEnabled()) {
//                    logger.debug("鉴定节点[" + this.getId() + "]选择的迁移:" +
//                            transitionNames[i]);
//                }
            logger.debug("鉴定节点[" + this.getId() + "]选择的迁移:" +
                    transitionName);

            transition = this.getLeavingTransition(transitionName);

//                String expressEval = transitionNames[i];
//
//                //创建子令牌
//                String tokenName = getTokenName(parentToken, expressEval);
//
//                Token childToken = new Token(parentToken, tokenName, this);
//                //创建执行上下文
//                ExecutionContext childExecutionContext = new ExecutionContext(
//                        childToken);
//                //离开节点
//                leave(childExecutionContext, expressEval);
//            }

        } else {
            logger.debug(
                    "没有选择迁移名,将采用默认的迁移!");
            transition = getDefaultLeavingTransition();
        }

            //如果迁移为空,则抛出异常
            if (transition == null) {
                throw new RuntimeException("OrFork节点[" + this.getName() +
                        "] 没有指定或者配置任何离开迁移!");
            }

            //创建子令牌
//            String tokenName = getTokenName(parentToken, transition.getName());
//
//            Token childToken = new Token(parentToken, tokenName, this);
//            //创建执行上下文
//            ExecutionContext childExecutionContext = new ExecutionContext(
//                    childToken);

            leave(executeContext, transition);



    }

    public String getExpresstion() {
        return expresstion;
    }

    public void setExpresstion(String expresstion) {
        this.expresstion = expresstion;
    }

    public static void main(String[]a)
    {
        final ScriptEngineManager mgr = new ScriptEngineManager();
        final ScriptEngine engine = mgr.getEngineByName("JavaScript");
        Date d = new Date();

        ExecutorService executorService = Executors.newFixedThreadPool(100);

        for(int i=0;i<=1000;i++)
        {
        try
        {
            Thread t = new Thread()
            {
               public void run()
               {
                   try
                   {
                    String obj = (String)engine.eval("var o = 5+10+''; if(o=='15') 'true'; else 'false';");
                   }catch (Exception e)
                   {
                       e.printStackTrace();
                   }
               }
            } ;
            executorService.execute(t);
            //System.out.println(obj);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        }
        System.out.println(""+(new Date().getTime()-d.getTime()));
    }

}
